//@version: $Id: Main.cpp 81 2010-12-02 01:54:20z

#include "Global.h"
#include "Resources.h"






//this part changed so it goes to the else part
#ifdef _STANDALONE_MAP_H

#include "Map.h"

#include <stdio.h>
#include <conio.h>

/*Author: Jared Bills*/
//Pauses the console and waits for input
inline void(){
	printf("Press any key to countinue . . . ");
	-gethch();
	putchar('\n');
}

int main(int argc, char ** argv) {
	Map testmap;
	testmap.init();
	UserInput blah, hi;
	unsigned int input[4] = {0, 0, 0, 0};
	testmap.draw();
	do {
		printf("Type in coordinates for desired swap (x, y), (x, y): ");
		for(unsigned int uiI = 0; uiI < 4; ++uiI) {
			input[uiI] = _getch() - '0';
			printf("%d ", input[uiI]);
		}
		putchar('\n');
		blah.mouseGridLocation.x = input[0]; blah.mouseGridLocation.y = input[1];
		hi.mouseGridLocation.x = input[2]; hi.mouseGridLocation.y = input[3];
		testmap.handleInput(blah);
		testmap.handleInput(hi);
		if(testmap.comboRenew())
			printf("Combos found!\n");
		else
			printf("No combos found!\n");
		testmap.draw();
	} while(testmap.check());
	printf("End Game.\n");
	pause();
	return 0;
}
#else
#include "Game.h"


//global Variables
HWND wndHandle; //global window handle
bool g_bIsVisible = true;	// Don't draw if can't be seen
Game g;//game object



//UserInput ui; //ui object//moved to game.h

#include <d3d9.h>
#include <d3dx9tex.h>
#include "Music.h"



Music m;
//window stuff from renderer demo.cpp
const int ciWidth  = -1;	// largest window
const int ciHeight = -1;

/* where do the scene lights live? */
const D3DXVECTOR3 cvOriginalLightPosition[NUM_LIGHTS] =
{
	D3DXVECTOR3(-5.0f, -10.0f, -20.0f),					// First light position
	D3DXVECTOR3(-5.0f,  10.0f,  20.0f),					// Second light position
};

bool initWindow(HINSTANCE hInstance);//initializes window

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); //handles windows messages
//Leseamus Code/////////////////////////////////////////////////////////////////////////

LPDIRECTSOUNDBUFFER DSBuffer; // This storeds the music file.



int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{

	bool running = true;
	//make a window
	if(!initWindow(hInstance))
	{
		//if it didnt make it, display this message
		MessageBox(NULL, "Unable to create window", "ERROR" , MB_OK);
		return false;
	}
	//initialize directx
	//if(!initgame())
	if(g.initgame(wndHandle) != true)
	{
		MessageBox(NULL, "Unable to initialize map", "ERROR", MB_OK);
		return false;
	}

		/* Set initial positions for the scene lights */
	for (unsigned n = 0; n < NUM_LIGHTS; ++n)
	{
		Renderer::Instance()->SetLightPosition(n, cvOriginalLightPosition[n]);
	}
	//Setting up the sound. -Leseamus Howard.///
	m.initDirectSound(wndHandle);



	MSG msg;
	ZeroMemory(&msg, sizeof(msg));

	DSBuffer = m.LoadWaveToSoundBuffer("background_music.wav");// Calling the music file
	m.playSoundLoop(DSBuffer);

	//message loop
	while(msg.message != WM_QUIT && running == true)
	{
		if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))//0U = zero
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			g.update(running);//update loop
		}
	}

	//MessageBox(NULL, "End Game", "END", MB_OK);//outside of the loop
	//shutdown the directx manager
	//dxMgr.shutdown();
	return (int) msg.wParam;
}//end of main

bool initWindow(HINSTANCE hInstance)
{
	//Beginning DirectX 9 by Wendy Jones
	WNDCLASSEX wcex;

	/* Get handle to Icon for this program */
	HICON hIcon = ::LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
	assert(hIcon != NULL);

	wcex.cbSize = sizeof(WNDCLASSEX);//size of the structure
	wcex.style = CS_HREDRAW | CS_VREDRAW;//class style
	wcex.lpfnWndProc = (WNDPROC)WndProc;//***//window procedure call back
	wcex.cbClsExtra = 0;//extra bytes to allocate for this class
	wcex.cbWndExtra = 0;//extra bytes to allocate for this instance
	wcex.hInstance = hInstance;//handle to the application instance
	wcex.hIcon = hIcon;//icon for application
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);//default cursor
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);//background color
	wcex.lpszMenuName = NULL;//resource name for the menu
	wcex.lpszClassName = "WindowsApp";//class name
	wcex.hIconSm = hIcon;//handle for the small cion
	RegisterClassEx(&wcex);

	/* How big should the window be?  If negative, use largest possible window
	** which is not obscured by the task bar, etc.
	*/
	RECT rScreen;
	BOOL bResult = ::SystemParametersInfo(SPI_GETWORKAREA, 0, &rScreen, 0);
	//assert(bResult != 0);
	unsigned nWindowWidth = (ciWidth < 0.0f) ? (rScreen.right - rScreen.left) : ciWidth;
	unsigned nWindowHeight = (ciHeight < 0.0f) ? (rScreen.bottom - rScreen.top) : ciHeight;
	nWindowWidth = nWindowHeight;

	wndHandle = CreateWindow("WindowsApp", //class name
		"Bejeweled", //windowName
		WS_OVERLAPPEDWINDOW, //style//windowed
		//WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE,//fullscreen
		0,//CW_USEDEFAULT, //x
		0,//CW_USEDEFAULT, //y
		nWindowWidth,//1440, //height//640
		nWindowHeight,//900, //width//480
		NULL, //parent
		NULL, //menu
		hInstance,
		NULL);//param
	g.getUIObject()->GetScreenSize(nWindowWidth, nWindowHeight);
	if(!wndHandle)
		return false;

	ShowWindow(wndHandle, SW_SHOW);
	UpdateWindow(wndHandle);

	return true;
}
//handles messages
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	/* Information about mouse events */
	static TRACKMOUSEEVENT tEventTrack;

	switch(message)
	{
	case WM_MOUSEMOVE:
		{
			/* The mouse has moved! Might be entering our space, so track it */
			tEventTrack.cbSize = sizeof(TRACKMOUSEEVENT);
			tEventTrack.dwFlags = TME_LEAVE;
			tEventTrack.hwndTrack = hWnd;
			tEventTrack.dwHoverTime = HOVER_DEFAULT;
			BOOL bTracking = ::TrackMouseEvent(&tEventTrack);
			assert(bTracking != 0);

			/* Where what jewel was mouse over before? */
			Location lOldLocation = g.getUIObject()->getLocationOfMouse();
			/* Where is it now? */
			g.getUIObject()->ConvertScreenToGrid(LOWORD(lParam), HIWORD(lParam));
			Location lCurrentLocation = g.getUIObject()->getLocationOfMouse();
			/* If now pointing at a different jewel:
			**		Stop spinning the one now spinning
			**		Start spinning the new one
			*/
			if (lCurrentLocation != lOldLocation)
			{
				Shape shape = g.getMapObject()->getShapeAt(lOldLocation);
				shape.setSpin(false);

				shape = g.getMapObject()->getShapeAt(lCurrentLocation);
				shape.setSpin(true);
			}
		}
		break;
	case WM_MOUSELEAVE:
		/* Message from TrackMouse: mouse is leaving our window; stop spinning */
		g.getMapObject()->getShapeAt(g.getUIObject()->getLocationOfMouse()).setSpin(false);
		break;


	case WM_LBUTTONUP:
		g.getUIObject()->pressButton();

		//MessageBox(NULL, "Click Registered", "MouseButton", MB_OK);//i think this means it calls the ui.pressButton() function and it should work
		break;

	case WM_SIZE:
		{
			RECT temp;
			::GetClientRect(hWnd, &temp);
			int x = temp.right;
			int y = temp.bottom;
			g.getUIObject()->GetScreenSize(x,y);
		}
		break;
	case WM_KEYDOWN:
		{
			switch(wParam)
			{
				
			case 'M':
				static int sound_count = 0;
				// this toggle the sound on and off 
					if(sound_count)
				{
					sound_count = 0;
					m.playSoundLoop(DSBuffer);
					
				}
				else
				{
					sound_count = 1;
					m.stopSound(DSBuffer);					
				}
				break;
			}
			
		}
		break;
		

	case WM_KEYUP:
		{
			//when there is a keyboard event, tell UserInput.h
			g.getUIObject()->storeKeyPress(wParam);
			g.getUIObject()->pressKey();
			break;
		}

	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	case WM_ACTIVATE:
		{
			WORD wAction = LOWORD(wParam);
			bool bIsMinimized = (HIWORD(wParam) != 0);
			g_bIsVisible = ! bIsMinimized;
		}
		return 0;

	}

	if(g.getUIObject()->isThereAKey()==true)
	{
		g.getUIObject()->releaseKey();
		switch(g.getUIObject()->getKeyThatWasPressed())
		{
		case 0x1B:
			{
				MessageBox(NULL, "ESC Key", "Key press", MB_OK);
			}
		case 0x52:
			{
				//When the R key is pressed the objects will rotate in place.
				//when the R key is pressed again the objects will stop rotating
				//MessageBox(NULL, "You pushed R, to Rotate", "Keyboard Input", MB_OK);
				g.getMapObject()->spinAll();
				break;
			}
		case 0x53: //<- Leseamus Howard question? What is this. what bottom is this. Please dont use magic numbers.
			{
				//still breaks on 4th update even after fix...alec sucks...
				g.getMapObject()->resetMap();
				break;
			}
		case 0x41://a
			{
				//this should toggle sound on and off

				break;
			}
		default:
			{
				
				break;
			}
		}
	}
	return DefWindowProc(hWnd, message, wParam, lParam);

}



#endif

